<template>
  <a-modal
    v-model:visible="visible"
    draggable
    width="600px"
    @before-ok="handleBeforeOk"
    @cancel="handleChangeVisible"
    @close="close"
  >
    <template #title>
      {{
        formData.id
          ? `${$t('columns.operations.edit')}`
          : `${$t('searchTable.operation.create')}`
      }}岗位</template
    >
    <SelectPostBook
      ref="selectPostBookRef"
      :multiple="false"
      @change="handleChangePost"
    ></SelectPostBook>
    <SelectOrgBook
      ref="selectOrgBookRef"
      :multiple="true"
      @change="handleChangeOrg"
    ></SelectOrgBook>
    <a-form
      ref="formRef"
      :model="formData"
      class="form"
      :label-col-props="{ span: 6 }"
      :wrapper-col-props="{ span: 18 }"
    >
      <a-form-item
        field="code"
        label="岗位编码"
        :rules="[{ required: true, message: '请输入岗位编码' }]"
      >
        <a-input v-model="formData.code" placeholder="请输入岗位编码" />
      </a-form-item>
      <a-form-item
        field="leaderPositionId"
        label="岗位上级领导岗位"
        :rules="[{ required: true, message: '请输入岗位上级领导岗位' }]"
      >
        <a-input-tag
          disabled
          :model-value="postName"
          placeholder="请点击按钮选择岗位"
        >
          <template #suffix>
            <a-button
              type="text"
              @click="
                () => {
                  selectPostBookRef.handleChangeVisible();
                }
              "
            >
              <template #icon>
                <icon-plus />
              </template>
            </a-button>
          </template>
        </a-input-tag>
      </a-form-item>
      <a-form-item
        field="level"
        label="岗位级别"
        :rules="[{ required: true, message: '请选择岗位级别' }]"
      >
        <PositionLevelSelector
          v-if="visible === true"
          v-model="formData.level"
          @handleChangeSelector="handlePositionLevelChangeSelector"
        >
        </PositionLevelSelector>
      </a-form-item>
      <a-form-item
        field="name"
        label="岗位名称"
        :rules="[{ required: true, message: '请输入岗位名称' }]"
      >
        <a-input v-model="formData.name" placeholder="请输入岗位名称" />
      </a-form-item>
      <a-form-item
        field="orgList"
        label="岗位隶属的组织"
        :rules="[{ required: true, message: '请选择岗位隶属的组织' }]"
      >
        <a-input-tag
          disabled
          :model-value="orgName"
          placeholder="请点击按钮选择组织"
        >
          <template #suffix>
            <a-button
              type="text"
              @click="
                () => {
                  selectOrgBookRef.handleChangeVisible();
                }
              "
            >
              <template #icon>
                <icon-plus />
              </template>
            </a-button>
          </template>
        </a-input-tag>
      </a-form-item>
      <a-form-item field="simpleName" label="岗位简称">
        <a-input v-model="formData.simpleName" placeholder="请输入岗位简称" />
      </a-form-item>
      <a-form-item field="type" label="岗位类型">
        <a-input v-model="formData.type" placeholder="请输入岗位类型" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import {
    PositionVo,
    createPosition,
    editPosition,
    OrganizationVO,
  } from '@/api/position';
  import { OrgTreeVo } from '@/api/organization';

  defineProps({
    title: {
      type: String,
      default: '岗位管理',
    },
    portalData: {
      type: Array,
    },
    renderData: {
      type: Array,
    },
  });

  const formRef = ref();
  const selectPostBookRef = ref();
  const selectOrgBookRef = ref();
  const visible = ref(false);
  const postName = ref<string[]>();
  const orgName = ref<string[]>();
  const PositionForm = () => {
    return {
      id: '',
      code: '', // 岗位编码
      leaderPositionId: '', // 岗位的上级领导岗位
      level: '', // 岗位级别
      levelName: '', // 岗位等级名称
      name: '', // 岗位名称
      simpleName: '', // 岗位简称
      sysInnerFlag: '0', // 是否内置标识
      type: '', // 岗位类型
      orgList: [] as string[],
      organizationList: [] as OrganizationVO[],
    };
  };
  const formData = ref(PositionForm());
  const isEdit = ref(false);
  const handlePositionLevelChangeSelector = (id: string, obj: any) => {
    formData.value.level = id;
    formData.value.levelName = obj.levelName;
  };
  const handleChangePost = (list: PositionVo[]) => {
    formData.value.leaderPositionId = list.length > 0 ? list[0].id || '' : '';
    postName.value = list.length > 0 ? [list[0].name || ''] : ([] as string[]);
  };
  const handleChangeOrg = (list: OrgTreeVo[]) => {
    formData.value.orgList = list.map((item) => item.id || '');
    orgName.value = list.map((item) => item.name || '');
  };
  const handleChangeVisible = (obj: PositionVo, select?: string) => {
    visible.value = !visible.value;
    formData.value = PositionForm();
    if (obj && select === 'add') {
      formData.value.leaderPositionId = obj.leaderPositionId as string;
    }
    if (obj && select === 'edit') {
      isEdit.value = true;
      formData.value = JSON.parse(JSON.stringify(obj));
      formData.value.orgList = formData.value.organizationList.map(
        (item: OrganizationVO) => item.id
      );
      formData.value.leaderPositionId =
        formData.value.leaderPositionId === '-1'
          ? ''
          : formData.value.leaderPositionId;
    }
    visible.value = true;
  };
  const close = () => {
    visible.value = false;
    formData.value = PositionForm();
    formRef.value.clearValidate();
  };

  const emit = defineEmits(['refresh']);

  function handleBeforeOk(done: any) {
    formRef.value.validate((valid: any) => {
      if (valid) {
        done(false);
      } else if (formData.value.id) {
        editPosition(formData.value)
          .then(() => {
            Message.success('操作成功');
            emit('refresh');
            done();
          })
          .catch(() => {
            done(false);
          });
      } else {
        createPosition(formData.value)
          .then(() => {
            Message.success('操作成功');
            emit('refresh');
            done();
          })
          .catch(() => {
            done(false);
          });
      }
    });
  }

  defineExpose({ handleChangeVisible });
</script>
